/*
 * 文件名：QueryCarMoneyResponceHandler.java	 
 * 时     间：上午10:28:47
 * 作     者：Administrator       
 * 版     权： 2012-2022 湖南智软网络科技, 公司保留所有权利.
 * 联     系：http://www.073586.com/
 */
package com.message.handler.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeanUtils;
import org.springframework.context.ApplicationContext;

import com.cz073586.tools.util.JsonUtil;
import com.cz073586.tools.util.Log4jUtil;
import com.cz073586.tools.util.Tools;
import com.local.common.CommonContains;
import com.local.model.CarParkIn;
import com.local.model.LocalCoupon;
import com.local.model.LocalCouponCash;
import com.local.model.LocalPayBill;
import com.local.model.LocalPayBillCopy;
import com.local.service.face.CarInAndOutService;
import com.local.service.face.LocalCarInRepertoryService;
import com.local.service.face.LocalChargeByTimeCopyService;
import com.local.service.face.LocalCouponCashService;
import com.local.service.face.LocalCouponService;
import com.local.service.face.ParkwellChargeBytimeService;
import com.local.service.face.ParkwellPayBillService;
import com.message.entity.BillInfo;
import com.message.entity.CouponInfo;
import com.message.entity.PayInfo;
import com.message.entity.TransDataVo;
import com.message.handler.face.ResponceHandler;
import com.qianhai.common.constants.CommonContans;

/**
 * 类描述:批量查询车辆价格
 * 
 * @ClassName: QueryCarMoneyResponceHandler
 * @author Administrator
 * @date 2015年10月21日 上午10:28:47
 */
public class QueryCarMoneyResponceHandler implements ResponceHandler {

	private Log4jUtil log = Log4jUtil.getLog4j(QueryCarMoneyResponceHandler.class);

	@Override
	public TransDataVo resoponse(ApplicationContext srpingApp, TransDataVo transData) {
		// 返回查询信息列表
		TransDataVo<List<BillInfo>> result = new TransDataVo<List<BillInfo>>();

		try {
			if (!Tools.isEmpty(transData.getData())) {
				String dataStr = JsonUtil.getJsonString(transData.getData());
				// 云传递过来的数据
				List<BillInfo> cloudData = JsonUtil.fromJson(dataStr, List.class, BillInfo.class);

				// 查询车牌信息费用
				List<BillInfo> retunData = new ArrayList<BillInfo>();
				result.setData(retunData);

				for (BillInfo clBillInfo : cloudData) {
					BillInfo billInfo = new BillInfo();
					countCarNOMoney(srpingApp, clBillInfo.getCaroNo(), billInfo);
					retunData.add(billInfo);
					// 计算车牌相机价格

				} // end for

				result.setResult(CommonContans.STRUTS_SUCCESS);
			}
		} catch (Throwable t) {
			log.error("", t);
			result.setResult(CommonContans.STRUTS_ERROR);
		}

		return result;
	}

	/**
	 * 
	 * 方法描述： 计算车牌产生费用
	 * 
	 * @Title: countCarNOMoney @param @param carNo @param @param
	 * billInfo @return void @user Administrator 2015年10月21日 @throws
	 */
	public void countCarNOMoney(ApplicationContext srpingApp, String carNo, BillInfo billInfo) {
		ParkwellChargeBytimeService servevice = srpingApp.getBean(ParkwellChargeBytimeService.class);
		// 流水service
		// 流水service
		ParkwellPayBillService payBill = srpingApp.getBean(ParkwellPayBillService.class);
		// 商家电子优惠券service
		LocalCouponCashService localCouponCashService = srpingApp.getBean(LocalCouponCashService.class);
		// 计费规则
		ParkwellChargeBytimeService localChargeByTimeService = srpingApp.getBean(ParkwellChargeBytimeService.class);

		// 查询会员是否有效 service
		CarInAndOutService carInAndOutService = srpingApp.getBean(CarInAndOutService.class);

		// 进场仓库表
		LocalCarInRepertoryService localCarInRepertoryService = srpingApp.getBean(LocalCarInRepertoryService.class);

		// 通过车牌查询 最近一场进场且没出场的 车辆记录
		CarParkIn cpIn = payBill.selectCarNo(carNo);
		if (!Tools.isEmpty(cpIn)) {
			// 总停车费
			double priceResult = localChargeByTimeService.queryCarinBillMoney(cpIn.getUuid(), cpIn.getCreateTime(),
					new Date(System.currentTimeMillis()));

			// 最新一条流水记录
			LocalPayBillCopy lp = payBill.queryLastBillCopy(cpIn.getUuid());
			if (!Tools.isEmpty(lp) && !Tools.isEmpty(lp.getPayTime())) {
				// 最后一条支付时间
				Long lastPaTime = lp.getPayTime().getTime() + (15 * 1000);
				// 现在的时间
				Long now = new Date(System.currentTimeMillis()).getTime();
				if (lastPaTime > now) {
					priceResult = localChargeByTimeService.queryCarinBillMoney(cpIn.getUuid(), cpIn.getCreateTime(),
							lp.getPayTime());
				}
			}
			// 已存在的流水集合
			List<LocalPayBillCopy> listbillListCopy = payBill.queryListByCarInUuid(cpIn.getUuid());
			List<LocalPayBill> listbillList = new ArrayList<LocalPayBill>();
			if (!Tools.isEmpty(listbillListCopy) && listbillListCopy.size() != 0) {
				for (LocalPayBillCopy lpCopy : listbillListCopy) {
					LocalPayBill localPayBill = new LocalPayBill();
					BeanUtils.copyProperties(lpCopy, localPayBill);
					listbillList.add(localPayBill);
				}
			}

			// 返回电子代金券集合
			List<LocalCouponCash> li = localCouponCashService.queryCouponCashByCarNo(carNo);

			// 返回抵用劵集合
			List<CouponInfo> couponList = retCouponInfo(li, srpingApp);

			// 返回流水装换集合
			List<PayInfo> payInfoLsXu = retParkwellPayBillXu(listbillList, li, srpingApp);

			// 返回流水装换集合
			List<PayInfo> payInfoLs = retParkwellPayBill(listbillList, li, srpingApp);

			// 判断车辆类型，是否会员，白名单，黑名单
			Map<String,Object> map = carInAndOutService
					.getIdentityTypeByCarNo(carNo);
			String carNoType = (String) map.get("carNoType");

			// 系统会员,如果是会员/白名单 算出来的金额为0
			if (carNoType.equalsIgnoreCase("会员") || carNoType.equalsIgnoreCase("白名单")) {
				priceResult = 0d;
			}

			// 判断是否足够出场的金额
			Double pprice = new Double(priceResult);
			BigDecimal b = new BigDecimal(pprice.doubleValue());
			double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
			pprice = f1 * 100;
			// 统计已支付金额
			Double cashPrice = new Double(0d);
			if (!Tools.isEmpty(payInfoLsXu) && payInfoLsXu.size() > 0) {
				for (PayInfo bill : payInfoLsXu) {
					pprice -= bill.getPrice();
					cashPrice += bill.getPrice().doubleValue() / 100;
				}
			}
			billInfo.setStatus(!Tools.isEmpty(pprice) && pprice <= 0 ? "0" : "1");
			billInfo.setCaroNo(carNo);
			billInfo.setCarOutTime(new Date(System.currentTimeMillis()).getTime());
			System.out.println(billInfo.getCarOutTime());
			billInfo.setPrice(priceResult * 100);
			billInfo.setPayInfoLs(payInfoLs);
			billInfo.setCouponList(couponList);
			if (billInfo.getStatus().equalsIgnoreCase("0")) {
				// 满足出场时，通过入场时间，已支付的金额，查出还剩余多少秒出场!
				billInfo.setFreeSec(
						servevice.queryFreeSec(cpIn.getUuid(), Math.abs(cashPrice), cpIn.getCreateTime().getTime())
								.intValue() / 1000);
				/*
				 * Random random = new Random();
				 * billInfo.setFreeSec(random.nextInt(90000));
				 */
				// 如果是会员,倒计时为null
				if (carNoType.equalsIgnoreCase("会员") || carNoType.equalsIgnoreCase("白名单")) {
					billInfo.setFreeSec(null);
				}
			}
		}
	}

	public List<PayInfo> retParkwellPayBill(List<LocalPayBill> listbillList, List<LocalCouponCash> li,
			ApplicationContext srpingApp) {
		try {
			List<PayInfo> payInfoLs = new ArrayList<PayInfo>();
			if (!Tools.isEmpty(listbillList) && listbillList.size() > 0) {
				for (LocalPayBill pb : listbillList) {
					// 流水表，装换payInfo
					PayInfo pi = new PayInfo();
					pi.setPayTime(!Tools.isEmpty(pb.getPayTime()) ? pb.getPayTime().getTime()
							: new Date(System.currentTimeMillis()).getTime());
					pi.setPayType(!Tools.isEmpty(pb.getPayType()) ? pb.getPayTypeInt(pb.getPayType())
							: CommonContains.PAY_TYPE_OTHER);
					pi.setPrice(!Tools.isEmpty(pb.getPrice()) ? (int) (pb.getPrice() * 100) : 0);

					LocalCouponService localCouponService = srpingApp.getBean(LocalCouponService.class);
					List<LocalCoupon> pCouponLs = localCouponService.queryByBillUuid(pb.getPayBillUuid());
					if (!Tools.isEmpty(pCouponLs)) {
						for (LocalCoupon pc : pCouponLs) {
							PayInfo pic = new PayInfo();
							pic.setPayTime(!Tools.isEmpty(pc.getPayTime()) ? pc.getPayTime().getTime()
									: new Date(System.currentTimeMillis()).getTime());
							pic.setPayType(CommonContains.PAY_TYPE_OTHER);
							pic.setPrice(!Tools.isEmpty(pc.getCouponPrice()) ? (int) (pc.getCouponPrice() * 100) : 0);
							payInfoLs.add(pic);
						}
					}
					payInfoLs.add(pi);
				}

			}
			/*
			 * if (!Tools.isEmpty(li)) { for (LocalCouponCash pcCash : li) {
			 * PayInfo payInfo = new PayInfo(); payInfo.setPayTime(new
			 * Date(System.currentTimeMillis()).getTime());
			 * payInfo.setPayType(CommonContains.PAY_TYPE_COUPON_CASH);
			 * payInfo.setPrice(!Tools.isEmpty(pcCash.getPrice()) ?
			 * pcCash.getPrice().intValue() : 0); payInfoLs.add(payInfo); } }
			 */
			return payInfoLs;

		} catch (Exception e) {
			// TODO: handle exception
			return null;
		}
	}

	public List<CouponInfo> retCouponInfo(List<LocalCouponCash> li, ApplicationContext srpingApp) {
		try {
			List<CouponInfo> couponList = new ArrayList<CouponInfo>();
			if (!Tools.isEmpty(li)) {
				SimpleDateFormat ds = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				for (LocalCouponCash pcCash : li) {
					CouponInfo couponInfo = new CouponInfo();
					couponInfo
							.setBusinessName(!Tools.isEmpty(pcCash.getPartnerName()) ? pcCash.getPartnerName() : null);
					couponInfo.setCouponType(CommonContains.PAY_TYPE_COUPON_CASH);
					couponInfo.setCreateTime(!Tools.isEmpty(pcCash.getCreateTime()) ? ds.format(pcCash.getCreateTime())
							: ds.format(new Date()));
					couponInfo.setUseTime(
							!Tools.isEmpty(pcCash.getUseTime()) ? pcCash.getUseTime() : ds.format(new Date()));
					couponInfo.setPrice(!Tools.isEmpty(pcCash.getPrice()) ? (int) (pcCash.getPrice() * 100) : 0);
					couponList.add(couponInfo);
				}
			}
			return couponList;

		} catch (Exception e) {
			// TODO: handle exception
			return null;
		}
	}

	public List<PayInfo> retParkwellPayBillXu(List<LocalPayBill> listbillList, List<LocalCouponCash> li,
			ApplicationContext srpingApp) {
		try {
			List<PayInfo> payInfoLs = new ArrayList<PayInfo>();
			if (!Tools.isEmpty(listbillList) && listbillList.size() > 0) {
				for (LocalPayBill pb : listbillList) {
					// 流水表，装换payInfo
					PayInfo pi = new PayInfo();
					pi.setPayTime(!Tools.isEmpty(pb.getPayTime()) ? pb.getPayTime().getTime()
							: new Date(System.currentTimeMillis()).getTime());
					pi.setPayType(!Tools.isEmpty(pb.getPayType()) ? pb.getPayTypeInt(pb.getPayType())
							: CommonContains.PAY_TYPE_OTHER);
					pi.setPrice(!Tools.isEmpty(pb.getPrice()) ? (int) (pb.getPrice() * 100) : 0);

					LocalCouponService localCouponService = srpingApp.getBean(LocalCouponService.class);
					List<LocalCoupon> pCouponLs = localCouponService.queryByBillUuid(pb.getPayBillUuid());
					if (!Tools.isEmpty(pCouponLs)) {
						for (LocalCoupon pc : pCouponLs) {
							PayInfo pic = new PayInfo();
							pic.setPayTime(!Tools.isEmpty(pc.getPayTime()) ? pc.getPayTime().getTime()
									: new Date(System.currentTimeMillis()).getTime());
							pic.setPayType(CommonContains.PAY_TYPE_OTHER);
							pic.setPrice(!Tools.isEmpty(pc.getCouponPrice()) ? (int) (pc.getCouponPrice() * 100) : 0);
							payInfoLs.add(pic);
						}
					}
					payInfoLs.add(pi);
				}

			}
			if (!Tools.isEmpty(li)) {
				for (LocalCouponCash pcCash : li) {
					PayInfo payInfo = new PayInfo();
					payInfo.setPayTime(new Date(System.currentTimeMillis()).getTime());
					payInfo.setPayType(CommonContains.PAY_TYPE_COUPON_CASH);
					payInfo.setPrice(!Tools.isEmpty(pcCash.getPrice()) ? (int) (pcCash.getPrice() * 100) : 0);
					payInfoLs.add(payInfo);
				}
			}
			return payInfoLs;

		} catch (Exception e) {
			// TODO: handle exception
			return null;
		}
	}

	public static void main(String[] agrs) {
		List<BillInfo> list = new ArrayList<BillInfo>();
		list.add(new BillInfo());
		String data = JsonUtil.getJsonString(list);
		System.out.println(data);
		// 回转
		List back = JsonUtil.fromJson(data, list.getClass(), BillInfo.class);
		System.out.println();
	}

}
